<style>
    .layui-form-label {
        width: 90px;
    }

    .layui-input-block {
        margin-left: 120px;
    }

    #productCategoryId xm-select {
        min-height: 32px;
        line-height: 32px;
        border-radius: 4px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">单据号：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="receiptsNo" class="layui-input" type="text"
                                               placeholder="输入单据号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">时间段：</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="createTime" id="pTime" class="layui-input date-icon" type="text"
                                               placeholder="选择时间" style="width: 200px" readonly/>
                                    </div>
                                    <input name="startCreateTime" id="sTime" type="hidden"/>
                                    <input name="endCreateTime" id="eTime" type="hidden"/>
                                </div>
                                <div class="layui-inline" style="margin-left: 5px;">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="purchasePlanBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                            <!--<button id="erpPurchasePlanCheck-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>普通计划核对</button>
                            <button id="erpPurchasePlanCheck-btn-add1" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>紧急计划核对</button>-->
                            <!--<button id="purchasePlanCheckBtnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>-->
                        </div>
                        <div class="lay-btn-rt">

                        </div>
                    </div>
                </div>
            </div>

            <!-- 表格 -->
            <table class="layui-table" id="purchasePlanCheckTable" lay-filter="purchasePlanCheckTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="erpPurchasePlanCheck-table-bar">
    {{# if(!d.hasGenerateOrder){ }} <!--没有生单并且已经盘点后才能生成请购单--><!-- && d.status == 2-->
    <a class="layui-btn layui-btn layui-btn-xs" lay-event="generate">生成请购单</a>
    {{# } }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">详情</a>
</script>


<!-- erpPurchasePlanCheck表单弹窗 -->
<script type="text/html" id="erpPurchasePlanCheck-form">
    <form lay-filter="erpPurchasePlanCheck-form" class="layui-form open-form">
        <div class="open-model">
            <div class="open-auto" style="padding-top: 5px;">
                <!-- 头部操作栏 -->
                <div class="layui-form lay-header">
                    <div class="toolbar">
                        <div class="layui-form-item lay-query-content">
                            <div class="lay-query-box">
                                <div class="query-lt">
                                    <!--                                    <div class="layui-inline">-->
                                    <!--                                        <label class="layui-form-label">部门：</label>-->
                                    <!--                                        <div class="layui-input-inline mr0">-->
                                    <!--                                            <select id="departmentId" lay-search></select>-->
                                    <!--                                        </div>-->
                                    <!--                                    </div>-->
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料分类：</label>
                                        <div class="layui-input-inline mr0">
                                            <input id="productCategory" placeholder="请输入物料分类" type="text"
                                                   maxlength="50" class="layui-input"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料编号：</label>
                                        <div class="layui-input-inline mr0">
                                            <input id="code" placeholder="请输入物料编号" type="text" maxlength="50"
                                                   class="layui-input"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料名称：</label>
                                        <div class="layui-input-inline mr0">
                                            <input id="name" placeholder="请输入物料名称" type="text" maxlength="50"
                                                   class="layui-input"/>
                                        </div>
                                    </div>
                                </div>
                                <div class="query-rt">
                                    <div class="layui-inline">
                                        <!--<div id="erpPurchasePlanCheck-list-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</div>-->
                                        <div class="layui-btn icon-btn color-green"
                                             id="erpPurchasePlanCheck-list-btn-search">查询
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <table class="layui-table" id="erpPurchasePlanCheck-add-table"
                       lay-filter="erpPurchasePlanCheck-add-table"></table>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
                <button class="layui-btn" lay-filter="erpPurchasePlanCheck-form-submit" lay-submit>保存</button>
            </div>
        </div>
    </form>
</script>

<!-- erpPurchasePlanCheck表单弹窗 -->
<script type="text/html" id="erpPurchasePlanCheck-form1">
    <form lay-filter="erpPurchasePlanCheck-form" class="layui-form model-form">
        <div class="layui-form-item">
            <div class="layui-col-xs6">
                <label class="layui-form-label">计划单号</label>
                <div class="layui-input-block">
                    <input id="planNo" name="planNo" placeholder="请输入计划单号" type="text" maxlength="50"
                           class="layui-input"/>
                </div>
            </div>
            <div class="layui-col-xs6">
                <label class="layui-form-label"></label>
                <div id="erpPurchasePlanCheck-list-btn-search" class="layui-btn icon-btn"><i
                        class="layui-icon">&#xe615;</i>搜索
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单据号<span style="color:red;">*</span></label>
            <div class="layui-input-block">
                <input name="receiptsNo" id="receiptsNo" placeholder="请输入单据号" type="text" maxlength="50"
                       class="layui-input" lay-verify="required|isOnly" required disabled="disabled"/>
            </div>
        </div>
        <div style="margin-left: 50px;">
            <table class="layui-table" id="erpPurchasePlanCheck-add-table"
                   lay-filter="erpPurchasePlanCheck-add-table"></table>
        </div>

        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
            <button class="layui-btn" lay-filter="erpPurchasePlanCheck-form-submit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- erpPurchasePlanCheck表单弹窗 -->
<script type="text/html" id="erpPurchasePlanCheck-edit">
    <form lay-filter="erpPurchasePlanCheck-edit" class="layui-form open-form">
        <div class="open-model">
            <div class="open-auto" style="padding-top: 5px;">
                <input name="id" type="hidden"/>
                <table class="layui-table" id="erpPurchasePlanCheck-add-table"
                       lay-filter="erpPurchasePlanCheck-add-table"></table>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="erpPurchasePlanCheckBusinessTypeId">
    <option value="">请选择业务类型</option>
    {{# layui.each(d, function(index, item){ }}
    <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
    {{# }) }}
</script>

<script type="text/html" id="erpPurchasePlanCheckDepartmentId">
    <option value="">请选择部门</option>
    {{# layui.each(d, function(index, item){ }}
    <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
    {{# }) }}
</script>

<script type="text/html" id="erpPurchasePlanCheckInventoryClassId">
    <option value="">请选择物料分类</option>
    {{# layui.each(d, function(index, item){ }}
    {{#
    var space = "";
    if(item.grade > 0){
    for(var j = 0; j < item.grade; j++){
    space += "&nbsp;&nbsp;";
    }
    }
    var disabled = "";
    if(item.isDisable == 1 || item.isParent){
    disabled = "disabled";
    }
    }}
    <option value="{{item.id}}" {{disabled}}>{{space}}{{item.code}}-{{item.name}}</option>
    {{# }) }}
</script>


<!-- erpPurchaseRequisitions表单弹窗 -->
<script type="text/html" id="erpPurchaseRequisitions-form">
    <form lay-filter="erpPurchaseRequisitions-form" class="layui-form open-form">
        <div class="open-model">
            <div class="open-auto" style="padding-top: 5px;">
                <input type="hidden" name="purchasePlanCheckId">
                <table class="layui-table" id="erpPurchaseRequisitions-add-table"
                       lay-filter="erpPurchaseRequisitions-add-table"></table>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
                <button class="layui-btn" lay-filter="erpPurchaseRequisitions-form-submit" lay-submit>保存</button>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="erpPurchaseRequisitionsErpDepartmentId">
    <option value="">请选择部门</option>
    {{# layui.each(d, function(index, item){ }}
    <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
    {{# }) }}
</script>

<script type="text/html" id="erpPurchaseRequisitionsBusinessTypeId">
    <option value="">请选择业务类型</option>
    {{# layui.each(d, function(index, item){ }}
    <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
    {{# }) }}
</script>

<script type="text/html" id="erpInventoryList">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar">
                <input id="erpInventoryList-code" class="layui-input search-input" type="text"
                       placeholder="输入物料编号"/>&emsp;
                <input id="erpInventoryList-name" class="layui-input search-input" type="text"
                       placeholder="输入物料名称"/>&emsp;
                <select id="erpInventoryList-way">
                    <option value="">请选择计价方式</option>
                    <option value="1">全月平均</option>
                    <option value="2">移动平均</option>
                    <option value="3">先进先出</option>
                    <option value="4">个别计价</option>
                </select>&emsp;
                <select id="erpInventoryList-erpInventoryClassId" lay-search></select>&emsp;
                <button id="erpInventoryList-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索
                </button>
                <button id="erpInventoryList-btn-choose" class="layui-btn layui-btn-normal">确认选择</button>
            </div>
            <table class="layui-table" id="erpInventoryList-table" lay-filter="erpInventoryList-table"></table>
        </div>
    </div>
</script>

<script type="text/html" id="erpInventoryListErpInventoryClassId">
    <option value="">请选择物料分类</option>
    {{# layui.each(d, function(index, item){ }}
    <option value="{{item.id}}">{{item.code}}-{{item.name}}</option>
    {{# }) }}
</script>

<script type="text/html" id="quantity">
    {{# var quantity = "";
    var isRequired = false;
    if(d.quantity != null){
    quantity = d.quantity;
    isRequired = true;
    }
    }}
    <div><input name="quantity" placeholder="请输入数量" type="text" value="{{quantity}}"
                lay-verify="{{isRequired ? 'required|quantity' : ''}}" required="{{isRequired ? true : false}}"
                class="layui-input" maxlength="10" style="border: 0;height: 28px;text-align:center;"/></div>
</script>

<script type="text/html" id="rate">
    {{# var rate = "";
    if(d.rate != null){
    rate = d.rate;
    }
    }}
    <div><input name="rate" placeholder="请输入税率" type="text" value="{{rate}}" lay-verify="rate" class="layui-input"
                maxlength="10" style="border: 0;height: 28px;text-align:center;"/></div>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="erpPurchaseRequisitions-add-table-bar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laytpl', 'laydate', 'util'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;
        var util = layui.util;

        //时间范围
        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function (value, date, endDate) {
                if (value) {
                    var dateValue = value.split(" - ");
                    $("#sTime").val(dateValue[0] + " 00:00:00");
                    $("#eTime").val(dateValue[1] + " 23:59:59");
                } else {
                    $("#sTime").val("");
                    $("#eTime").val("");
                }
            }
        });

        // 渲染表格
        var insTb = table.render({
            elem: '#purchasePlanCheckTable',
            url: config.base + 'enterprise/purchase/admin/purchasePlanCheck/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            where: {
                access_token: config.getToken().access_token
            },
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'},
                {field: 'receiptsNo', align: 'center', title: '单据号'},
                {field: 'creatorName', align: 'center', title: '制单人'},
                {field: 'createTime', align: 'center', title: '核对时间'},
                // {field: 'statusName',align: 'center', title: '盘点状态'},
                {
                    align: 'center', title: '是否全部转成请购单', templet: function (d) {
                        return d.hasGenerateOrder ? "是" : "否";
                    }
                },
                {align: 'center', toolbar: '#erpPurchasePlanCheck-table-bar', title: '操作', width: '20%'}
            ]]
        });

        // 添加按钮点击事件
        $('#purchasePlanBtnAdd').click(function () {
            showEditModel(1);
        });

        // 添加按钮点击事件
        $('#erpPurchasePlanCheck-btn-add1').click(function () {
            showEditModel(2);
        });

        // 工具条点击事件
        table.on('tool(purchasePlanCheckTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (obj.event === 'generate') { //生成采购订单
                // generate(data);
                openForm('generate', data.id);
            } else if (obj.event === 'view') { //详情
                // showViewModel(data);
                openForm('view', data.id);
            }
        });

        function openForm(eventName, id) {
            const titleobj = {
                'generate': '新增请购单信息',
                'view': '领料单核对详情'
            }
            admin.req('enterprise/purchase/admin/purchasePlanCheckDetail/list', {
                limit: 9999,
                checkId: id
            }, (res) => {
                if (res.code === 200) {
                    admin.formOpen({
                        title: titleobj[eventName],
                        area: ['90%', '80%'],
                        offset: '50px',
                        path: 'components/purchase/purchasePlanCheckForm.html',
                        success: function () {
                            parentData.data = res.data;
                            parentData.id = id;
                            parentData.eventName = eventName;
                        }
                    })
                } else {
                    layer.msg(res.msg);
                }
            })
        }

        //显示表单弹窗
        var showEditModel = function (type) {
            admin.open({
                type: 1,
                area: ['1300px', '80%'],
                title: '新增领料单核对信息',
                content: $('#erpPurchasePlanCheck-form').html(),
                success: function () {
                    var dataList = [];
                    var erpPurchasePlanCheckDetails = []; //明细数据
                    findCheckInfoList(1);
                    // 搜索按钮点击事件
                    $('#erpPurchasePlanCheck-list-btn-search').click(function () {
                        var productCategory = $('#productCategory').val();
                        var departmentId = $("#departmentId").val();
                        var productName = $("#name").val();
                        var skuCode = $("#code").val();
                        findCheckInfoList(2, productCategory, departmentId, productName, skuCode);
                    });

                    //自定义验证规则
                    form.verify({
                        quantity: [/^([1-9]\d*(\.\d{1,2})?|([0](\.([0][0-9][1-9]|[1-9]\d{0,1})))|[ \t]*)$/, '格式错误']
                    })

                    // 获取部门
                    // admin.req('user/admin/department/list', {limit:9999}, function (res) {
                    //     if (res.code == 200) {
                    //         var html='<option value="">请选择部门</option>';
                    //         for(var k=0;k<res.data.length;k++){
                    //             html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                    //         }
                    //         $("#departmentId").html(html);
                    //         form.render('select');
                    //     } else {
                    //         layer.msg('获取部门失败', {icon: 2, time: 1000});
                    //     }
                    // }, 'GET');

                    //加载物料分类树级菜单
                    /*admin.req('enterprise/product/admin/productCategory/getProductCategoryByType', {type: 0}, function (res) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].children = [];
                        }
                        var arr2tree = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                        var smlSelectInstans = xmSelect.render({
                            el: '#productCategoryId',
                            model: {label: {type: 'text'}},
                            radio: true,
                            clickClose: true,
                            filterable: true,
                            tree: {
                                show: true,
                                strict: false,
                                expandedKeys: [-1],
                            },
                            tips: '请选择物料分类',
                            prop: {
                                name: 'name',
                                value: 'id',
                                children: 'children'
                            },
                            data() {
                                //填充数据
                                return arr2tree;
                            },
                            on(data) {
                                let parentId = data.arr.length > 0 ? data.change[0].id : "";
                                $("input[name='productCategoryId']").val(parentId);
                            }
                        });
                    }, 'get', false);*/

                    function findCheckInfoList(type, productCategory, departmentId, productName, skuCode) {
                        dataList = [];
                        // 获取未核对领料计划的一些详情
                        admin.req('enterprise/purchase/admin/purchasePlanCheck/findCheckInfoList',
                            {
                                productCategory: productCategory,
                                departmentId: departmentId,
                                productName: productName,
                                skuCode: skuCode
                            },
                            function (data) {
                                layer.closeAll('loading');
                                if (data.code == 200) {
                                    var detail = data.data;
                                    for (var i = 0; i < detail.length; i++) {
                                        dataList.push({});
                                        dataList[i].skuCode = detail[i].skuCode;
                                        dataList[i].productName = detail[i].productName;
                                        dataList[i].unitName = detail[i].unitName;
                                        dataList[i].productDetailId = detail[i].productDetailId;
                                        dataList[i].specifications = detail[i].specifications ? detail[i].specifications : "";
                                        dataList[i].checkNumber = detail[i].checkNumber ? detail[i].checkNumber : "";
                                        dataList[i].departmentName = detail[i].departmentName ? detail[i].departmentName : "";
                                        dataList[i].productCategory = detail[i].productCategory ? detail[i].productCategory : "";

                                        if (type == 1) {
                                            erpPurchasePlanCheckDetails.push({});
                                            erpPurchasePlanCheckDetails[i].purchasePlanDetailId = detail[i].id;
                                            erpPurchasePlanCheckDetails[i].skuCode = detail[i].skuCode;
                                            erpPurchasePlanCheckDetails[i].productName = detail[i].productName;
                                            erpPurchasePlanCheckDetails[i].unitName = detail[i].unitName;
                                            erpPurchasePlanCheckDetails[i].specifications = detail[i].specifications ? detail[i].specifications : "";
                                            erpPurchasePlanCheckDetails[i].checkNumber = detail[i].checkNumber ? detail[i].checkNumber : "";
                                            erpPurchasePlanCheckDetails[i].productCategory = detail[i].productCategory ? detail[i].productCategory : "";
                                            erpPurchasePlanCheckDetails[i].productDetailId = detail[i].productDetailId
                                        }
                                    }
                                    // 渲染表格
                                    table.render({
                                        elem: '#erpPurchasePlanCheck-add-table',
                                        data: dataList,
                                        limit: dataList.length,
                                        cols: [[
                                            {type: 'numbers'},
                                            // {field: 'departmentName',align: 'center', title: '部门'},
                                            {field: 'productCategory', align: 'center', title: '物料分类', },
                                            {field: 'productName', align: 'center', title: '物料名称', },
                                            {field: 'skuCode', align: 'center', title: '物料编号', },
                                            {field: 'specifications', align: 'center', title: '规格型号', },
                                            {field: 'unitName', align: 'center', title: '采购单位', },
                                            {field: 'checkNumber', title: '领料计划数量', align: 'center', width: 130}
                                        ]],
                                        done: function () {
                                            $("input[name='purchaseNumber']").on("input", function (e) {
                                                //获取input输入的值
                                                var curValue = e.delegateTarget.value;
                                                var curIndex = $(this).closest("tr").data("index");
                                                if (erpPurchasePlanCheckDetails[curIndex]) {
                                                    erpPurchasePlanCheckDetails[curIndex].purchaseNumber = curValue;
                                                }
                                                usualData[curIndex].purchaseNumber = curValue;
                                                if (usualData.length - curIndex - 1 < 10) {
                                                    var addLength = 10 - (usualData.length - curIndex - 1);
                                                    for (var i = 0; i < addLength; i++) {
                                                        usualData.push({});
                                                    }
                                                }
                                            });
                                            layer.closeAll('loading');
                                        }
                                    });
                                } else {
                                    layer.msg(data.msg, {icon: 2, time: 1000});
                                }
                            }, 'GET');
                    }

                    // 表单提交事件
                    form.on('submit(erpPurchasePlanCheck-form-submit)', function (data) {
                        if (erpPurchasePlanCheckDetails.length > 0) {
                            data.field.checkInfos = erpPurchasePlanCheckDetails;
                            layer.load(2);
                            admin.req('enterprise/purchase/admin/purchasePlanCheck/add', JSON.stringify(data.field), function (data) {
                                layer.closeAll('loading');
                                if (data.code == 200) {
                                    layer.msg(data.msg, {icon: 1, time: 500});
                                    table.reload('purchasePlanCheckTable');
                                    layer.closeAll('page');
                                } else {
                                    layer.msg(data.msg, {icon: 2, time: 1000});
                                }
                            }, 'POST', false, "application/json");
                        } else {
                            layer.msg("未输入发生数据，无法保存", {icon: 2, time: 1000});
                        }
                        return false;
                    });
                }
            })
        };

        //详情
        var showViewModel = function (data) {
            admin.open({
                type: 1,
                area: ['1200px', '800px'],
                title: '领料单核对详情',
                content: $('#erpPurchasePlanCheck-edit').html(),
                success: function () {

                    //获取明细数据
                    admin.req('enterprise/purchase/admin/purchasePlanCheckDetail/list', {
                        limit: 9999,
                        checkId: data.id
                    }, function (data) {
                        if (200 == data.code) {
                            var detail = data.data;
                            // 渲染表格
                            table.render({
                                elem: '#erpPurchasePlanCheck-add-table',
                                data: detail,
                                limit: detail.length,
                                height: 430,
                                cols: [[
                                    {type: 'numbers'},
                                    // {field: 'departmentName',align: 'center', title: '部门',},
                                    {field: 'productCategory', align: 'center', title: '物料分类',},
                                    {field: 'productName', align: 'center', title: '物料名称',},
                                    {field: 'skuCode', align: 'center', title: '物料编号',},
                                    {field: 'specifications', align: 'center', title: '规格型号',},
                                    {field: 'unitName', align: 'center', title: '采购单位',},
                                    {field: 'checkNumber', title: '领料计划数量', align: 'center', width: 140},
                                    {field: 'surplusQuantity', title: '剩余领料数量', align: 'center', width: 140},
                                    {
                                        title: '已请购领料数量', align: 'center', width: 140, templet(d) {
                                            return Number(d.checkNumber) - Number(d.surplusQuantity);
                                        }
                                    },
                                ]]
                            });

                        } else {
                            layer.msg('获取明细失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                }
            })
        };


        // 生成采购订单
        var generate = function (data) {
            admin.open({
                type: 1,
                area: ['80%', '85%'],
                title: '新增请购单信息',
                content: $('#erpPurchaseRequisitions-form').html(),
                success: function () {
                    var dataList = [];
                    var purchaseRequisitionsDetails = []; //明细数据
                    var usualData = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];
                    var codeArr = [];//物料选择集合
                    $("input[name='purchasePlanCheckId']").val(data.id);

                    //自定义验证规则
                    form.verify({
                        quantity: [/^([0-9]\d*(\.\d{1,3})?|([0](\.([0][0-9][0-9]|[0-9]\d{0,2})))|[ \t]*)$/, '格式错误'],
                        rate: [/^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1})))|[ \t]*)$/, '格式错误']
                    })


                    findPurchaseRequisitionsList("init");

                    // 搜索按钮点击事件
                    $('#erpPurchaseRequisitions-add-search').click(function () {
                        var businessType = $("#businessType").val();
                        findPurchaseRequisitionsList("search", businessType);
                    });

                    function findPurchaseRequisitionsList(type) {
                        dataList = [];
                        // 获取明细数据
                        admin.req('enterprise/purchase/admin/purchasePlanCheckDetail/getPurchasePlanCheckDetail', {checkId: data.id}, function (data) {
                            console.log(data);
                            if (200 == data.code) {
                                var detail = data.data;
                                for (var i = 0; i < detail.length; i++) {
                                    dataList.push({});
                                    dataList[i].skuCode = detail[i].skuCode;
                                    dataList[i].productName = detail[i].productName;
                                    dataList[i].unitName = detail[i].unitName;
                                    dataList[i].specifications = detail[i].specifications ? detail[i].specifications : "";
                                    //计算  请购数量 = （领料数量 - 现存量） > 0 ? （领料数量 - 现存量） ： 0
                                    var checkNumber = detail[i].checkNumber; //领料数量
                                    dataList[i].quantity = checkNumber;
                                    if (type == "init") {
                                        purchaseRequisitionsDetails.push({});
                                        purchaseRequisitionsDetails[i].skuCode = detail[i].skuCode;
                                        purchaseRequisitionsDetails[i].productName = detail[i].productName;
                                        purchaseRequisitionsDetails[i].unitName = detail[i].unitName;
                                        purchaseRequisitionsDetails[i].specifications = detail[i].specifications ? detail[i].specifications : "";
                                        purchaseRequisitionsDetails[i].quantity = checkNumber;
                                    }
                                    usualData.push({});
                                    usualData[i].quantity = checkNumber;
                                    codeArr.push(detail[i].skuCode);
                                }

                                // 渲染表格
                                table.render({
                                    elem: '#erpPurchaseRequisitions-add-table',
                                    data: dataList,
                                    limit: dataList.length,
                                    height: 430,
                                    cols: [[
                                        {type: 'numbers'},
                                        {
                                            field: 'productName',
                                            align: 'center',
                                            title: '物料名称',
                                            width: 140
                                        },
                                        {
                                            field: 'skuCode',
                                            align: 'center',
                                            title: '物料编号',
                                            width: 120
                                        },
                                        {field: 'specifications', align: 'center', title: '规格型号', width: 140},
                                        {
                                            field: 'unitName',
                                            align: 'center',
                                            title: '采购单位',
                                            width: 100
                                        },
                                        {
                                            field: 'checkNumber',
                                            align: 'center',
                                            title: '领料计划数量',
                                            width: 100
                                        },
                                        {
                                            align: 'center',
                                            title: '剩余领料数量',
                                            width: 100,
                                            templet: function (d) {
                                                return Number(d.checkNumber) - Number(d.surplusQuantity);
                                            }
                                        },
                                        {
                                            title: '数量',
                                            align: 'center',
                                            // templet: '#quantity',
                                            width: 100,
                                            templet: admin.setTableInput('quantity')
                                        },
                                        {
                                            title: '税率(%)',
                                            align: 'center',
                                            // templet: '#rate',
                                            width: 100,
                                            templet: admin.setTableInput('rate')
                                        },
                                        {
                                            align: 'center',
                                            toolbar: '#erpPurchaseRequisitions-add-table-bar',
                                            title: '操作',
                                            width: 100
                                        }
                                    ]],
                                    done: function () {
                                        $("input[name='quantity']").on("input", function (e) {
                                            //获取input输入的值
                                            var curValue = e.delegateTarget.value;
                                            var curIndex = $(this).closest("tr").data("index");
                                            if (purchaseRequisitionsDetails[curIndex]) {
                                                purchaseRequisitionsDetails[curIndex].quantity = curValue;
                                            }
                                            usualData[curIndex].quantity = curValue;
                                            if (usualData.length - curIndex - 1 < 10) {
                                                var addLength = 10 - (usualData.length - curIndex - 1);
                                                for (var i = 0; i < addLength; i++) {
                                                    usualData.push({});
                                                }
                                            }
                                        });
                                        $("input[name='rate']").on("input", function (e) {
                                            //获取input输入的值
                                            var curValue = e.delegateTarget.value;
                                            var curIndex = $(this).closest("tr").data("index");
                                            if (purchaseRequisitionsDetails[curIndex]) {
                                                purchaseRequisitionsDetails[curIndex].rate = curValue;
                                            }
                                            usualData[curIndex].rate = curValue;
                                            if (usualData.length - curIndex - 1 < 10) {
                                                var addLength = 10 - (usualData.length - curIndex - 1);
                                                for (var i = 0; i < addLength; i++) {
                                                    usualData.push({});
                                                }
                                            }
                                        });
                                        layer.closeAll('loading');
                                    }
                                });

                            } else {
                                layer.msg('获取明细失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');

                        // 工具条点击事件
                        table.on('tool(erpPurchaseRequisitions-add-table)', function (obj) {
                            var data = obj.data;
                            var layEvent = obj.event;
                            if (obj.event === 'del') { //删除
                                doDelete(obj);
                            }
                        });

                        // 删除
                        var doDelete = function (obj) {
                            var index = $(obj.tr).data("index");
                            if (!$.isEmptyObject(obj.data)) {
                                layer.confirm('确定要删除吗？', {
                                    offset: '65px',
                                    skin: 'layui-layer-admin'
                                }, function (i) {
                                    layer.close(i);
                                    //obj.del();
                                    dataList.splice(index, 1);
                                    purchaseRequisitionsDetails.splice(index, 1);
                                    usualData.splice(index, 1);
                                    if (codeArr.indexOf(obj.data.skuCode) >= 0) {
                                        codeArr.splice(codeArr.indexOf(obj.data.skuCode), 1);
                                    }
                                    if ($.isEmptyObject(dataList[0])) {
                                        dataList = [];
                                        // 获取数据集合并传入请购单中
                                        table.reload('erpPurchaseRequisitions-add-table', {
                                            data: [],
                                            limit: 0,
                                        });
                                    } else {
                                        // 获取数据集合并传入请购单中
                                        table.reload('erpPurchaseRequisitions-add-table', {
                                            data: dataList,
                                            limit: dataList.length
                                        });
                                    }
                                });
                            }
                        };
                    }

                    // 表单提交事件
                    form.on('submit(erpPurchaseRequisitions-form-submit)', function (d) {
                        if (purchaseRequisitionsDetails.length > 0) {
                            d.field.purchaseRequisitionsDetails = purchaseRequisitionsDetails;
                            console.log(d.field);
                            layer.load(2);
                            admin.req('enterprise/purchase/admin/purchasePlanCheck/addPurchaseRequisitions', JSON.stringify(d.field), function (res) {
                                layer.closeAll('loading');
                                if (res.code == 200) {
                                    layer.msg(res.msg, {icon: 1, time: 500});
                                    table.reload('purchasePlanCheckTable');
                                    layer.closeAll('page');
                                } else {
                                    layer.msg(res.msg, {icon: 2, time: 1000});
                                }
                            }, 'POST', false, "application/json");
                        } else {
                            layer.msg("未输入发生数据，无法保存", {icon: 2, time: 1000});
                        }
                        return false;
                    });

                }
            })
        }

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        // 导出excel
        $('#purchasePlanCheckBtnExport').click(function () {
            var checkRows = table.checkStatus('purchasePlanCheckTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>